<template>
  <div class="container" v-loading="isLoading">
    <div class="main-content">
      <el-card>
        <el-button-group>
          <el-upload  ref="upload" :action="uploadAction"  :show-file-list="false" :on-change="readExcelUpdate" :auto-upload="false" style="float: left;">
            <el-button slot="trigger" icon="el-icon-upload" size="small" title="导入职位信息" type="primary">导入职位信息</el-button>
          </el-upload>
          <el-upload v-show="isShow" ref="upload" :action="uploadAction"  :show-file-list="false" :on-change="readExcelAdd" :auto-upload="false" style="float: left;">
            <el-button slot="trigger" icon="el-icon-upload" size="small" title="导入职位信息" type="primary">导入职位信息</el-button>
          </el-upload>
          <el-button size="small" title="下载模板" @click="onDownloadTmp">点击下载模板</el-button>
        </el-button-group>
      </el-card>
    </div>
    <el-table :data="tmpDataList" id="download" style="display: none;">
      <el-table-column type="index" label="序号" ></el-table-column>
      <el-table-column prop="project" label="项目" ></el-table-column>
      <el-table-column prop="jobTitle" label="招聘岗位" ></el-table-column>
      <el-table-column prop="jobType" label="职能名称" ></el-table-column>
      <el-table-column prop="jobDesc" label="岗位职责" ></el-table-column>
      <el-table-column prop="requirement" label="任职要求" ></el-table-column>
      <el-table-column prop="workPlace" label="工作地点" ></el-table-column>
      <el-table-column prop="applyUrl" label="链接" ></el-table-column>
    </el-table>
    <el-dialog title="导入结果" :visible.sync="dialogErrorVisible" width="800px" :close-on-click-modal="false">
      <h4>共计<strong> {{totalCount}} </strong>条记录，成功：<strong style="color:green"> {{successCount}} </strong>条，
        失败：<strong style="color:red"> {{errorCount}} </strong>条 </h4>
      <el-button  @click="onDownloadError" style="float: right; margin-bottom: 10px"  size="small"  type="primary" plain title="点击下载错误记录" v-if="errorList.length>0">下载错误记录</el-button>
      <el-table :data="errorList"  style="max-height:600px; overflow-y: auto;"  v-if="errorList.length>0">
        <el-table-column prop="index" label="错误行" ></el-table-column>
        <el-table-column prop="field" label="字段" ></el-table-column>
        <el-table-column prop="val" label="值" ></el-table-column>
        <el-table-column prop="reason" label="失败原因" ></el-table-column>
      </el-table>
    </el-dialog>
    <el-table :data="errorDataList" id="downloadError" style="display: none;">
      <el-table-column prop="sort" label="序号" ></el-table-column>
      <el-table-column prop="project" label="项目" ></el-table-column>
      <el-table-column prop="jobTitle" label="招聘岗位" ></el-table-column>
      <el-table-column prop="jobType" label="职能名称" ></el-table-column>
      <el-table-column prop="jobDesc" label="岗位职责" ></el-table-column>
      <el-table-column prop="requirement" label="任职要求" ></el-table-column>
      <el-table-column prop="workPlace" label="工作地点" ></el-table-column>
      <el-table-column prop="applyUrl" label="链接" ></el-table-column>
      <el-table-column prop="reason" label="失败原因" ></el-table-column>
    </el-table>

  </div>
</template>

<script>
  import XLSX from 'xlsx'
  import FileSaver from 'file-saver'
  import {importExcel} from "../../api/job/mengniu";

  export default {
    components: {},
    data(){
      return{
        isLoading:false,
        token:{'token':this.$store.state.token},
        uploadAction:'', //上传图片地址
        tmpDataList:[{
          project:'优益生',
          jobTitle:'软件验证工程师', // 招聘岗位
          jobType: '技术研发类', // 岗位类别
          jobDesc:'1、负责...', // 岗位职责
          requirement:'1、本科及以上以上...', // 任职要求
          workPlace:'杭州', // 工作地点
          applyUrl:'猎聘职位地址'
        }],
        dialogErrorVisible:false, //显示错误信息
        errorList:[],  //上传会员信息 有误的
        successCount:0,  //成功条数
        errorCount:0,  //失败条数
        totalCount:0,  //共计
        errorDataList:[],
          isShow:false
      }
    },
    watch:{
      dialogErrorVisible:function (val,oldVal) {
        if(val == false && oldVal == true){
          this.errorList = [];
        }
      }
    },
    methods:{
      //下载模板
      onDownloadTmp(){
        var wb = XLSX.utils.table_to_book(document.querySelector("#download"));
        console.log("wb===>",wb);
        var ws = wb.Sheets.Sheet1;
        ws['!cols']= [{wpx: 105},{wpx: 105}, {wpx: 100},{wpx: 100},{wpx: 105}, {wpx: 105}, {wpx:105}, {wpx:300}];

        var wbout = XLSX.write(wb, {bookType: "xlsx", bookSST: true, type: "array"});
        try {
          FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "岗位模板.xlsx");
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },
      //下载错误信息
      onDownloadError(){
        var wb = XLSX.utils.table_to_book(document.querySelector("#downloadError"));
        console.log("wb===>",wb);
        var ws = wb.Sheets.Sheet1;
        ws['!cols']= [{wpx: 105},{wpx: 105}, {wpx: 100},{wpx: 100},{wpx: 100},{wpx: 100},{wpx: 100},{wpx: 300},{wpx: 500}];
        for(var ww in ws){
          XLSX.utils.cell_set_number_format(wb.Sheets.Sheet1[ww],'@');
        }

        var wbout = XLSX.write(wb, {bookType: "xlsx", bookSST: true, type: "array"});
        try {
          FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "上传失败记录.xlsx");
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;

      },
        readExcelUpdate(file){
            this.readExcel(file, 'update');
        },
        readExcelAdd(file){
          this.readExcel(file, 'add');
        },
      //上传
      readExcel(file, type) {
        this.isLoading = true;
        var suffix = file.name.split(".")[1]
        if(suffix != 'xls' && suffix !='xlsx'){
          this.isLoading = false;
          this.$message.warning('文件类型不正确！');
          return false;
        }
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            for (let sheet in workbook.Sheets) {
              const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
              if(sheetArray!=null && sheetArray.length >0){
                console.log("sheetArray",sheetArray);
                this.importData({mapList:sheetArray, type:type});
              }
            }
            // this.$message.success('导入完成！');
          }catch (e) {
            this.isLoading = false;
            this.$message.warning('文件类型不正确！');
            return false;
          }
        };
        this.isLoading = false;
        fileReader.readAsBinaryString(file.raw);
      },
      async importData(sheetArray){
        this.isLoading = true;
        let resp = await importExcel(sheetArray);
        console.log("====resp",resp);
        if(!this.qUtil.validResp(resp)){
          this.$message.error(resp.errMsg || '导入失败')
          this.isLoading = false;
          return false;
        }
        // this.$message.success('数据已导入!')
        this.isLoading = false;

        this.errorList = resp.data.errorList || [];
        this.errorDataList = resp.data.errorDataList || [];
        this.successCount = resp.data.successCount;
        this.errorCount = resp.data.errorCount;
        this.totalCount = resp.data.totalCount;
        this.dialogErrorVisible = true;
      }
    },
    mounted(){
    }
  }
</script>

<style scoped>
</style>

